import './css/index.less';

const imgDomList = [...document.querySelectorAll('.lazy-loader')];

window.addEventListener('scroll', throttle(lazyLoad), false);

lazyLoad();

function lazyLoad() {
    for(let i = 0; i < imgDomList.length; i++) {
        const imgDom = imgDomList[i];

        if (isInVisibleArea(imgDom)) {
            imgLoad(imgDom.dataset.src)
                .then(imgLoadSuccess(imgDom))
                .catch(imgLoadFail(imgDom));
            imgDomList.splice(i, 1);
            i--;
        }
    };
}

function isInVisibleArea(dom) {
    const rect = dom.getBoundingClientRect();
    const screenHeight = window.innerHeight;
    const screenWidth = window.innerWidth;

    return rect.bottom >= 0 && rect.top <= screenHeight &&
        rect.left <= screenWidth && rect.right >= 0;
}

function throttle(fn, limitTime = 250, context) {
    let lastTimestamp = 0;
    return (...args) => {
        const now = new Date().getTime();
        const self = context || this;
        if (now - lastTimestamp > limitTime) {
            fn.apply(self, args);
        }
    };
}

function imgLoad(url) {
    return new Promise((resolve, reject) => {
        const img = new Image();

        img.src = url;
        img.onload = () => {
            resolve(img)
        };
        img.onerror = () => {
            reject(img);
        };
    })
}

function imgLoadSuccess(dom) {
    return () => {
        dom.src = dom.dataset.src;
    }
}

function imgLoadFail(dom) {
    let count = 0
    return (tImg) => {
        if(navigator.onLine) {
            if (count <= 3) {
                tImg.src = tImg.src;
                count++;
                return;
            } else {
                dom.src = '';
                console.log('图片请求失败');
            }
        }else {
            setTimeout(() => {
                tImg.src = tImg.src;
            }, 500);
        }
    }
}